﻿using System;
using System.Collections.Generic;
using System.Reflection;

namespace _5E.Utils.ReflectionHelper
{
    /// <summary>
    /// 程序说明：动态方法缓存
    /// 创建作者：ahl
    /// 创建时间：2012-03-25
    /// </summary>
    public class DynamicMethodCache
    {
        #region 变量

        /// <summary>
        /// 互斥体
        /// </summary>
        private object m_Mutex = new object();

        /// <summary>
        /// 缓存
        /// </summary>
        private Dictionary<Type, Dictionary<MethodInfo, DynamicMethod>> m_DicCache =
            new Dictionary<Type, Dictionary<MethodInfo, DynamicMethod>>();

        #endregion

        #region 普通方法

        public DynamicMethod GetAccessor(MethodInfo method)
        {
            DynamicMethod accessor;
            Dictionary<MethodInfo, DynamicMethod> dicTypeCache;
            if (m_DicCache.TryGetValue(method.ReflectedType, out dicTypeCache))
            {
                if (dicTypeCache.TryGetValue(method, out accessor))
                {
                    return accessor;
                }
            }
            lock (m_Mutex)
            {
                if (dicTypeCache == null)
                {
                    dicTypeCache = new Dictionary<MethodInfo, DynamicMethod>();
                    m_DicCache.Add(method.ReflectedType, dicTypeCache);
                }
                accessor = new DynamicMethod(method);
                dicTypeCache.Add(method, accessor);
            }
            return accessor;
        }

        #endregion
    }
}
